package io.netty.example.fep.netty.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * Description：
 * 自定义msg（header+length+content）加码器
 *
 * @author : chenjie03@imdada.cn
 * Date: 2020/5/26
 * Time: 13:48
 */
public class FepProtocolEncoder extends MessageToByteEncoder<FepProtocolMsg> {

    /**
     * 加码；
     * 将msg写入buf中；
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to
     * @param msg the message to encode
     * @param out the {@link ByteBuf} into which the encoded message will be written
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, FepProtocolMsg msg, ByteBuf out) throws Exception {
        if (msg == null) {
            throw new Exception("msg is null");
        }
        out.writeByte(msg.getType());
        byte[] bytes4Body = msg.getBody().getBytes(Charset.forName("UTF-8"));
        out.writeInt(bytes4Body.length);
        out.writeBytes(bytes4Body);
    }
}
